<template>
    <div class="container">
        <div>
          <el-button type="text" ><router-link to="/">首页</router-link></el-button>
        </div>
        <div class="content">
          <h2>极速文件上传</h2>
          <el-upload
              class="upload-demo"
              drag
              :action="url"
              :auto-upload="true"
              :file-list="fileList"
              :show-file-list="false"
              :on-change="handleChange"
              :on-success="handleSuccess">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <!-- 显示上传成功的文件列表 -->
          <el-table :data="fileList" style="width: 100%">
            <el-table-column prop="name" label="文件名"></el-table-column>
            <el-table-column label="下载地址">
              <template slot-scope="scope">
                <a :href="scope.row.url" target="_blank">{{ scope.row.name }}</a> <!-- 下载链接 -->
              </template>
            </el-table-column>
            <el-table-column prop="displaySize" label="文件大小"></el-table-column>
          </el-table>
        </div>
    </div>
  </template>

<script>
export default {
  data() {
    return {
      url: "/api/chunkUpload",
      fileList: [],
      fileSize: null, 
    };
  },
  methods: {
    handleChange(file, fileList) {
      this.fileSize = file.size
    },
    handleSuccess(response, file, fileList) {
      // 文件上传成功的回调
      let displaySize;
      
      if (this.fileSize < 1024) {
        displaySize = `${this.fileSize} B`;
      } else if (this.fileSize < 1048576) {
        displaySize = `${(this.fileSize / 1024).toFixed(2)} KB`;
      } else {
        displaySize = `${(this.fileSize / 1048576).toFixed(2)} MB`;
      }
      
      const uploadedFile = {
        name: file.name,
        url: `/api/downloadPart?fileName=${file.name}&fileSize=${this.fileSize}`,
        displaySize: displaySize
      };
      this.fileList.push(uploadedFile);
      this.$message.success({
          title: '成功',
          message: '上传文件成功!',
          type: 'success'
        });
    },
  }
}
</script>

<style scoped>
.content {
  text-align: center;
  width: 100%; /* 确保容器宽度为100% */
}
.upload-demo {
  display: block; /* 将其设为块级元素 */
  margin: 20px auto; /* 垂直和水平居中 */
  width: fit-content; /* 根据内容自适应宽度 */
}

</style>
